package com.android.fragmentdemo.definervlayoutmanager;
import android.graphics.Canvas;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

public class CardItemTouchCallback extends ItemTouchHelper.Callback {

    private final ICardCallback mCardCallback;

    public CardItemTouchCallback(ICardCallback mCardCallback) {
        this.mCardCallback = mCardCallback;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        mCardCallback.onItemRemove(viewHolder.getAdapterPosition());
    }

    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,
                            float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

        float distance = (float) Math.hypot(dX, dY);
        float maxDistance = recyclerView.getWidth() / 2.0f;

        float fraction = Math.min(1, distance / maxDistance);
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View child = recyclerView.getChildAt(i);
            int level = CardConfig.SHOW_MAX_COUNT - i - 1;
            if (CardConfig.SHOW_MAX_COUNT - 1 == level) {
                child.setTranslationY(CardConfig.TRANSLATION_Y * (level - 1));
                float scaleValue = 1 - CardConfig.SCALE * (level - 1);
                child.setScaleX(scaleValue);
                child.setScaleY(scaleValue);
            } else if (level > 0) {
                child.setTranslationY(CardConfig.TRANSLATION_Y * level - fraction * CardConfig.TRANSLATION_Y);
                float scaleValue = 1 - CardConfig.SCALE * level + fraction * CardConfig.SCALE;
                child.setScaleX(scaleValue);
                child.setScaleY(scaleValue);
            }
        }
    }

    @Override
    public float getMoveThreshold(@NonNull RecyclerView.ViewHolder viewHolder) {
        return 0.3f;
    }

    @Override
    public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
        return makeMovementFlags(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
    }

    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        return false;
    }
}
